﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        private bool isok;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Filldata();
            }
        }
        private void Filldata()
        {
            var sql = "select * from Articles";
            var dt = DbHelper.GetDataTable (sql);

            gv1.DataSource = dt;
            gv1.DataBind();

        }

        private string GetValue(int rowIndex, int collndtx)
        {
            var count = gv1.Rows[rowIndex].Cells[collndtx];
            var value = count.Controls.Count > 0 ? ((TextBox)count.Controls[0]).Text : count.Text;
            return value;
        }
        protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = int.Parse(GetValue(e.RowIndex, 0));
            var sql = string.Format("delete from Student where id={0}", id);

        }

        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv1.EditIndex = e.NewEditIndex;
            Filldata();
        }

        protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv1.EditIndex = -1;
            Filldata();
        }

        protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var Title = GetValue(e.RowIndex, 1);
            var Content= GetValue(e.RowIndex, 2);
            var Author = GetValue(e.RowIndex, 3);
            var tempVlaue = GetValue(e.RowIndex, 0);

            var isok = int.TryParse(tempVlaue, out int id);
            if (isok)
            {
                var sql = string.Format("update Articles set Title='{0}',Countent='{1}' tuthor='{2}' where='{3}'", Title, Content, Author, id);
                DbHelper.AddOrUpdateOrDelete(sql);
            }
            else
            {
                var sql = string.Format("insert into Student(StudentName)values('{0}','{1}','{2}')",Title,Content,Author);
                DbHelper.AddOrUpdateOrDelete(sql);
            }
            gv1.EditIndex = -1;
            Filldata();
        }


    }
}

    

        





